package com.webserver.controller;

import com.webserver.core.ClientHandler;
import com.webserver.entity.Article;
import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.URISyntaxException;

public class ArticleController {
    private static File rootDir,staticDir;
    private static File articleDir;

    static {
        try {
            rootDir = new File(ClientHandler.class.getClassLoader().getResource(".").toURI());
            staticDir = new File(rootDir,"static");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        articleDir = new File("articles");
        if(!articleDir.exists()){
            articleDir.mkdirs();
        }
    }


    public void writeArticle(HttpServletRequest request, HttpServletResponse response){
        String title = request.getParameter("title");
        String author = request.getParameter("author");
        String content = request.getParameter("content");

        if(title == null || author == null || content == null){
            File file = new File(staticDir,"/myweb/article_info_error.html");
            response.setContentFile(file);
            return;
        }

        File articleFile = new File(articleDir,title + ".obj");
        if(articleFile.exists()){
            File file = new File(staticDir,"/myweb/have_article.html");
            response.setContentFile(file);
            return;
        }
        Article article = new Article(title,author,content);
        try (
                FileOutputStream fos = new FileOutputStream(articleFile);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
        ){
            oos.writeObject(article);
            File file = new File(staticDir,"/myweb/article_success.html");
            response.setContentFile(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
